import threading
from threading import Thread
from time import sleep


# Create your views here.
import os
import django
import subprocess
from oplatform.machine_code import machine_code_auth

os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'IPTVOPlatform.settings')
django.setup()
from oplatform.models import ConfigurationData
from utils.write_channel import write_config_file
running_pids = []


@machine_code_auth
def run_channels():
    configs = ConfigurationData.objects.filter(status=2)
    global running_pids
    if len(configs) == 0:
        kill_all_cmd = "ps -ef | grep channel | grep -v grep | awk '{print $2}' | xargs kill -9"
        subprocess.Popen(kill_all_cmd, shell=True, stdout=subprocess.PIPE)
    for config in configs:
        config_id = config.id
        cmd = "ps aux | awk '{if($13~/\/channel" + str(config_id) + ".conf$/)print $2}'"
        before_pid = subprocess.getoutput(cmd)
        if before_pid == '':
            write_config_file(config)
            args = '/opt/media -c ' + '/var/www/channels/channel' + str(config_id) + '.conf -d --card ' + str(config_id - 1)
            p = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE)
            try:
                pid = p.pid
                running_pids.append({'channel_id': config_id, 'pid': pid})
            except:
                config.status = 1
                config.save()
        else:
            running_pids.append({'channel_id': config_id, 'pid': before_pid})


def listen_running_channels():
    global running_pids
    configs = ConfigurationData.objects.all()
    for config in configs:
        config_id = config.id
        cmd = 'ps aux | grep  channel' + str(config_id) + ' | grep -v grep'
        if subprocess.getoutput(cmd) == '':
            config.status = 1
            config.save()
            for pid in running_pids:
                if pid['channel_id'] == config_id:
                    running_pids.remove(pid)


def listen_stopping_channels():
    global running_pids
    configs = ConfigurationData.objects.all()
    for config in configs:
        config_id = config.id
        cmd = 'ps aux | grep  channel' + str(config_id) + ' | grep -v grep'
        if subprocess.getoutput(cmd) != '':
            config_ids = []
            for pid in running_pids:
                config_ids.append(pid['channel_id'])
            if config_id not in config_ids:
                config.status = 2
                config.save()
                cmd = "ps aux | awk '{if($13~/\/channel" + str(config_id) + ".conf$/)print $2}'"
                pid = subprocess.getoutput(cmd)
                running_pids.append({'channel_id': config_id, 'pid': pid})


def run_timer():
    while True:
        sleep(5)
        listen_running_channels()
        listen_stopping_channels()


run_channels()
Thread(target=run_timer).start()
